// @ts-nocheck
import { Router } from 'preact-router';
import { signal } from '@preact/signals';
import { useEffect } from 'preact/hooks';
import Sidebar from './components/Sidebar';
import Welcome from './pages/Welcome';
import DeviceStatus from './pages/DeviceStatus';
import Settings from './pages/Settings';
import OnboardPeripherals from './pages/OnboardPeripherals';
import EtherCATSlave from './pages/EtherCATSlave';

// 全局状态
export const isConnected = signal(false);
export const deviceInfo = signal({});
export const currentPath = signal(window.location.pathname);
export const cpuUsageHistory = signal(Array(301).fill(0));
export const memoryUsageHistory = signal(Array(301).fill(0));
export const temperatureHistory = signal(Array(301).fill(0));

// 主题状态管理
export const isDarkTheme = signal(() => {
  const saved = localStorage.getItem('adonis-theme');
  if (saved) {
    return saved === 'dark';
  }
  return window.matchMedia('(prefers-color-scheme: dark)').matches;
});

// 主题切换函数
export const toggleTheme = () => {
  // 添加全局过渡动画
  document.body.classList.add('theme-transitioning');
  
  isDarkTheme.value = !isDarkTheme.value;
  localStorage.setItem('adonis-theme', isDarkTheme.value ? 'dark' : 'light');
  applyTheme();
  
  // 移除动画类
  setTimeout(() => {
    document.body.classList.remove('theme-transitioning');
  }, 300);
};

// 应用主题到DOM
export const applyTheme = () => {
  const root = document.documentElement;
  if (isDarkTheme.value) {
    root.classList.add('dark');
    root.classList.remove('light');
  } else {
    root.classList.add('light');
    root.classList.remove('dark');
  }
};

// EtherCAT相关状态
export const ethercatData = signal({
  digitalInputs: 0,        // 16位数字输入 (位掩码)
  digitalOutputs: 0,       // 16位数字输出 (位掩码)
  syncPeriod: 0,           // 同步周期 (μs)
  dcSyncStatus: 'INIT',    // 同步状态: INIT, PREOP, SAFEOP, OP
  syncMode: 'FreeRun',     // 同步模式: Freerun, SM, DC
  slaveALStatus: 'INIT',   // 从站状态
});

export function App() {
  // 初始化主题
  useEffect(() => {
    applyTheme();
  }, []);

  return (
    <div class="flex h-screen">
      <Sidebar />
      <main class="flex-1 overflow-x-hidden overflow-y-auto">
        <div class="container mx-auto px-6 py-8">
          <Router>
            <Welcome path="/" />
            <DeviceStatus path="/device-status" />
            <OnboardPeripherals path="/onboard-peripherals" />
            <EtherCATSlave path="/ethercat-slave" />
            <Settings path="/settings" />
          </Router>
        </div>
      </main>
    </div>
  );
} 